package pppp.hhhh.redisdemo.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import pppp.hhhh.redisdemo.entity.User;
import pppp.hhhh.redisdemo.mapper.UserMapper;

import java.time.Duration;

@Service
public class UserService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    private static final String USER_CACHE_KEY_PREFIX = "user:";

    // 获取用户信息
    public User getUserById(Long id) {
        String cacheKey = USER_CACHE_KEY_PREFIX + id;

        // 1. 从 Redis 获取缓存
        User user = (User) redisTemplate.opsForValue().get(cacheKey);
        if (user != null) {
            return user;
        }

        // 2. 缓存不存在，从数据库查询
        user = userMapper.getUserById(id);
        if (user != null) {
            redisTemplate.opsForValue().set(cacheKey, user, Duration.ofMinutes(10));
        }
        return user;
    }

    // 更新用户信息（延迟双删策略）
    public void updateUser(User user) {
        String cacheKey = USER_CACHE_KEY_PREFIX + user.getId();

        // 1. 先删除缓存
        redisTemplate.delete(cacheKey);

        // 2. 更新数据库
        userMapper.updateUser(user);

        // 3. 延迟双删：等待一小段时间再删除缓存，防止并发导致缓存数据不一致
        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        // 4. 再次删除缓存，确保数据一致性
        redisTemplate.delete(cacheKey);
    }

    // 删除用户
    public void deleteUser(Long id) {
        String cacheKey = USER_CACHE_KEY_PREFIX + id;

        // 1. 删除缓存
        redisTemplate.delete(cacheKey);

        // 2. 删除数据库中的记录
        userMapper.deleteUser(id);

        // 延迟双删：再次删除缓存
        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        redisTemplate.delete(cacheKey);
    }

    public void insertUser(User user) {
        // 插入数据库
        userMapper.insertUser(user);

        // 插入之后，缓存该用户信息
        String cacheKey = USER_CACHE_KEY_PREFIX + user.getId();
        redisTemplate.opsForValue().set(cacheKey, user, Duration.ofMinutes(10));
    }
}
